//index.js
//获取应用实例
const app = getApp()
const gd = app.globalData
const utils = require('../../utils/util.js')
const getLocation = utils.wxPromisify(wx.getLocation)
const request = utils.wxPromisify(wx.request)
const setStorage = utils.wxPromisify(wx.setStorage)
Page({
  data: {
    weatherNow:{},
    airNow:{},
    current: 'index',
    airColor:'',
    future:{},
    cond_code:100
  },
  onLoad: function () {
    this.initData()
  },
  initData(){
    wx.showLoading({
      title: '加载中',
    })
    const weatherNow = wx.getStorageSync('weatherNow')
    const airNow = wx.getStorageSync('airNow')
    const future = wx.getStorageSync('future')
    getLocation({
      type: 'wgs84'
    }).then(res => {
      let prams = {
        location: res.longitude + ',' + res.latitude,
        key: gd.apikey
      }
      if (weatherNow && airNow) {
        this.setData({
          weatherNow: weatherNow[0],
          airNow: airNow[0],
        })
        this.setAirColor(airNow[0].air_now_city.aqi)
      } else {
        utils.requestJsonData(gd.apinow, prams, 'weatherNow').then(res => {
          this.setData({
            weatherNow: res[0]
          })
          prams.location = res[0].basic.parent_city
          utils.requestJsonData(gd.apiairnow, prams, 'airNow').then(res => {
            console.log(res)
            this.setData({
              airNow: res[0]
            })
            this.setAirColor(res[0].air_now_city.aqi)
          })

        })
      }
      if (future) {
        this.setData({
          future: future[0]
        })
      } else {
        utils.requestJsonData(gd.apifuture, prams, 'future').then(res => {
          this.setData({
            future: res[0]
          })
          wx.stopPullDownRefresh()
        })
      }
      wx.hideLoading()
    })
  },
  handleChange({ detail }) {
    if(detail.key == 'nearby'){
      wx.redirectTo({
        url: '/pages/near/near',
      })
    }
    this.setData({
      current: detail.key
    })
  },
  setAirColor(num){
    let airColor = ''
    if (num <= 50) {
      airColor = 'green'
    } else if (num <= 150) {
      airColor = 'yellow'
    } else if (num <= 500) {
      airColor = 'red'
    }
    this.setData({
      airColor
    })
  },
  onPullDownRefresh:function(){
    wx.clearStorage()
    this.initData()
  }
})
